package gui;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;

import details.Cd;
import details.Like;
import details.Target;
import details.Track;

import runnable_functions.ReferedObject;
import runnable_functions.USERfunctions;

/**
 * Logging Dialog ============== presents stores table for selection by user
 * program is initiated by selected store's view
 */
public class AlbumSearchResultsDialog extends org.eclipse.swt.widgets.Dialog {
	private static Display display;
	private static AlbumSearchResultsDialog inst;
	private static Shell shell;
	private static Shell dialogShell;
	private static Button searchDialogButtonSearchAlbum;
	private static Button searchDialogButtonSearchSong;
	private static Group logDialogGroup;

	private static Text searchDialogAlbumTitleText;
	private static Text searchDialogAlbumPerformerText;
	private static Text searchDialogAlbumGenreText;
	private static Text searchDialogAlbumYearFromText;
	private static Text searchDialogAlbumYearToText;

	private static Text searchDialogSongTitleText;
	private static Text searchDialogSongArtistText;
	private static Text searchDialogSongLyricText;
	private static int press = 1;

	Color color = new Color(display, 8, 164, 199);

	public static boolean successful = false;

	static Image background = new Image(display,Main.class.getResourceAsStream("headphone-music1.jpg"));
	static Image background2 = new Image(display,Main.class.getResourceAsStream("headphone-music2.jpg"));
	// Search results group
	private static Group searchGroupResults;
	private static Table searchTableAlbumResults;
	private static TableColumn searchTableColumnAlbum;
	private static TableColumn searchTableColumnArtist;
	private static TableColumn searchTableColumnYear;
	private static TableColumn searchTableColumnGenre;

	//Album Details
	private static Group searchGroupDetails;
	private static Table searchTableSongResults;
	private static TableColumn searchTableColumnSongTrack;
	private static TableColumn searchTableColumnSongName;
	private static TableColumn searchTableColumnSongLength;
	private static Button searchButtonShowLyric;

	// Search options group
	private static Group searchGroupOptions;
	private static Button searchCheckBoxArtist;
	private static Text searchTextBoxArtist;
	private static Button searchCheckBoxSong;
	private static Text searchTextBoxSong;
	private static Button searchCheckBoxAlbum;
	private static Text searchTextBoxAlbum;
	private static Button searchCheckBoxLyric;
	private static Text searchTextBoxLyric;
	private static Button searchCheckBoxYear;
	private static Text searchTextBoxYear;
	private static Button searchCheckBoxGenre;
	private static Text searchTextBoxGenre;
	private static Button searchButtonClear;
	private static Button searchButtonSearch;
	private static Image cDcover;
	private static Button searchButtonShowSongs;
	private static ArrayList<Cd> searchResult;
	private static String[] columnNames = {"Title", "Artist", "Genre", "Year"};
	private static Group cd_cover;
	private static Image cDcover1 = new Image(display,Main.class.getResourceAsStream("no-cover.jpg"));
	private static Color white = new Color(display, 255, 255, 255);
	private static Cd desireCd;
	private static Button delete;
	private static Button update;
	private static boolean isLike;
	//private static boolean permitedLikeAct;

	/**
	 * Auto-generated main method to display this org.eclipse.swt.widgets.Dialog
	 * inside a new Shell.
	 */
	public static void openSearchDialog() {
		try {
			display = Display.getDefault();
			shell = new Shell(display);
			shell.setLocation(Main.getCentral_x() - 406,
					Main.getCentral_y() - 458);
			shell.setSize(398, 200);
			//shell.setBackgroundImage(background);
			inst = new AlbumSearchResultsDialog(shell, SWT.NULL);
			inst.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void closeInitDialog() {
		shell.close();
	}

	public AlbumSearchResultsDialog(Shell parent, int style) {
		super(parent, style);
	}

	public void open() {
		try {
			Shell parent = getParent();
			dialogShell = new Shell(parent, SWT.DIALOG_TRIM
					| SWT.APPLICATION_MODAL);

			dialogShell.setText("Music Box");
			//dialogShell.setBackgroundImage(background);
			dialogShell.setLayout(null);
			{
			
				{
					searchGroupResults = new Group(dialogShell, SWT.NONE);
					searchGroupResults.setLayout(null);
					searchGroupResults.setBackgroundImage(background);
					//searchGroupResults.setText("Search Results");
					searchGroupResults.setBounds(0, -8, 790, 215);
					{
						searchTableAlbumResults = new Table(searchGroupResults,
								SWT.BORDER | SWT.FULL_SELECTION | SWT.H_SCROLL
								| SWT.V_SCROLL | SWT.SINGLE); // single row
						// selection
						searchTableAlbumResults.setBounds(13, 23, 764, 148);
						searchTableAlbumResults.setHeaderVisible(true);
						searchTableAlbumResults.setLinesVisible(true);


						searchTableColumnAlbum = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnAlbum.setText("Title");
						searchTableColumnAlbum.setResizable(true);
						searchTableColumnAlbum.setMoveable(true);
						searchTableColumnAlbum.setWidth(275);


						searchTableColumnArtist = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnArtist.setText("Artist");
						searchTableColumnArtist.setResizable(true);
						searchTableColumnArtist.setMoveable(true);
						searchTableColumnArtist.setWidth(245);

						searchTableColumnGenre = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnGenre.setText("Genre");
						searchTableColumnGenre.setResizable(true);
						searchTableColumnGenre.setMoveable(true);
						searchTableColumnGenre.setWidth(122);

						searchTableColumnYear = new TableColumn(
								searchTableAlbumResults, SWT.NONE);
						searchTableColumnYear.setText("Year");
						searchTableColumnYear.setResizable(true);
						searchTableColumnYear.setMoveable(true);
						searchTableColumnYear.setWidth(100);


						searchResult = Main.guiInt.getCds();
						for (int i = 0; i < searchResult.size(); i++) {
							newEntry(searchResult.get(i).getTitle(),
									searchResult.get(i).getPerformer(),
									searchResult.get(i).getGenre(),
									searchResult.get(i).getReleaseYear());

						}

					}
					{
						
						
						
						searchButtonShowSongs = new Button(searchGroupResults,
								SWT.PUSH | SWT.CENTER);
						searchButtonShowSongs.setText("Show Album Details");
						searchButtonShowSongs.setBounds(245, 177, 340, 30);
						searchButtonShowSongs.addListener(SWT.Selection,
								new Listener() {
							public void handleEvent(Event event) {
								desireCd=null;
								URL url=null;
								
								Main.signal=null;
								cd_cover.setBackground(white);
								if (searchTableAlbumResults.getSelectionIndex()!= -1){
								int index = searchTableAlbumResults.getSelectionIndex();
								desireCd =  Main.guiInt.getCds().get(index);
								
								
									TableItem[] items = searchTableSongResults.getItems();
									for (int i = 0; i < items.length ; i++) {
									if (items.length == 0) break;
									items[i].dispose();
									}
								

								Main.signal = new CountDownLatch(2);
								Main.dbGui.getCdAllInfo(desireCd);		
								try {
									Main.signal.await();
								} catch (InterruptedException e) {
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setText("Error");
									messageBox.setMessage("Error: "
											+ e.getLocalizedMessage());
									messageBox.open();
									e.printStackTrace();
								}

								String guiErrorMsg = Main.guiInt.getMassage();
								if (guiErrorMsg != null){
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setText("Login Form");
									messageBox.setMessage("Error: "
											+ guiErrorMsg);
									messageBox.open();
								}else{			
									desireCd = Main.guiInt.getCd();
									Main.guiInt.setLikes(desireCd.getLikes());
									System.out.println("the number of desired cd's likes is "+ desireCd.getLikes());
									ArrayList<Track> desireCdTracks = desireCd.getTracks();

									for (int i = 0; i < desireCdTracks.size(); i++) {
										newSongEntry(desireCdTracks.get(i).getTrackNum(),
												desireCdTracks.get(i).getTitle(),
												desireCdTracks.get(i).getArtistName(),
												desireCdTracks.get(i).getLengthInSec());
									}
									
									 url=Main.guiInt.getCdCover();
									
									if (url!= null){
										
										
										try {
											cDcover = new Image(display, url.openStream());
											 cDcover = new Image(display,
													cDcover.getImageData().scaledTo(280,280));
											    
										} catch (IOException e) {
											MessageBox messageBox = new MessageBox(
													AlbumSearchResultsDialog.shell, 32);
											messageBox.setText("Error");
											messageBox.setMessage("Error: "
													+ e.getLocalizedMessage());
											messageBox.open();
										}
									}else{
										cDcover = new Image(display,Main.class.getResourceAsStream("no-cover.jpg"));
									}
										Main.signal = new CountDownLatch(1);
										Main.dbGui.getIfUserLike(Target.CD, desireCd.getAlbom_id(), Main.getUser().getIdNum());
										try {
											Main.signal.await();
										} catch (InterruptedException e) {
											MessageBox messageBox = new MessageBox(
													AlbumSearchResultsDialog.shell, 32);
											messageBox.setText("Error");
											messageBox.setMessage("Error: "
													+ e.getLocalizedMessage());
											messageBox.open();
											
										}
//popopo
										guiErrorMsg = Main.guiInt.getMassage();
										if (guiErrorMsg != null){
											MessageBox messageBox = new MessageBox(
													AlbumSearchResultsDialog.shell, 32);
											messageBox.setText("Song Search");
											messageBox.setMessage("Error: "
													+ guiErrorMsg);
											messageBox.open();
										}else{	
											isLike = Main.guiInt.getUserLike();
											
											if (isLike){
												searchButtonShowLyric.setText("unLike");
												searchDialogAlbumTitleText.setText("Likes: " + Main.guiInt.getLikes());	
											}else{
												searchButtonShowLyric.setText("Like");
												searchDialogAlbumTitleText.setText("Likes: " + Main.guiInt.getLikes());
											}
											
										}
										
										
									
									cd_cover.setBackgroundImage(cDcover);
									delete.setBounds(645, 177, 100, 30);
									update.setBounds(45, 177, 100, 30);
									searchDialogAlbumGenreText.setText("Views: " +desireCd.getViews());
									//searchDialogAlbumTitleText.setText("Likes: " +desireCd.getLikes());
									searchDialogAlbumGenreText.setBounds(315, 100, 80, 22);
									searchDialogAlbumTitleText.setBounds(315, 122, 80, 22);
									searchButtonShowLyric.setBounds(320, 190, 60, 30);

									
									
									
									
										
								
								}
							}
						}}
								);
					}
				}


				{
					searchGroupDetails = new Group(dialogShell, SWT.NONE | SWT.NO_BACKGROUND);
					searchGroupDetails.setLayout(null);
					searchGroupDetails.setBackgroundImage(background2);
					searchGroupDetails.setText("Album Details");
					searchGroupDetails.setBounds(5, 215, 787, 350);
					{
						searchTableSongResults = new Table(searchGroupDetails,
								SWT.BORDER | SWT.FULL_SELECTION | SWT.H_SCROLL
								| SWT.V_SCROLL | SWT.SINGLE);
						searchTableSongResults.setBounds(403, 23, 374, 280);
						searchTableSongResults.setHeaderVisible(true);
						searchTableSongResults.setLinesVisible(true);
						
						
						searchDialogAlbumTitleText = new Text(searchGroupDetails, SWT.None);
						
						
						
						
						searchDialogAlbumGenreText = new Text(searchGroupDetails, SWT.None);
						
						searchTableColumnSongTrack = new TableColumn(
								searchTableSongResults, SWT.NONE);
						searchTableColumnSongTrack.setText("Track");
						searchTableColumnSongTrack.setResizable(true);
						searchTableColumnSongTrack.setMoveable(true);
						searchTableColumnSongTrack.setWidth(50);


						searchTableColumnSongTrack = new TableColumn(
								searchTableSongResults, SWT.NONE);
						searchTableColumnSongTrack.setText("Title");
						searchTableColumnSongTrack.setResizable(true);
						searchTableColumnSongTrack.setMoveable(true);
						searchTableColumnSongTrack.setWidth(137);

						searchTableColumnSongName = new TableColumn(
								searchTableSongResults, SWT.NONE);
						searchTableColumnSongName.setText("Artist");
						searchTableColumnSongName.setResizable(true);
						searchTableColumnSongName.setMoveable(true);
						searchTableColumnSongName.setWidth(120);


						searchTableColumnSongLength = new TableColumn(
								searchTableSongResults, SWT.NONE);
						searchTableColumnSongLength.setText("Duration");
						searchTableColumnSongLength.setResizable(true);
						searchTableColumnSongLength.setMoveable(true);
						searchTableColumnSongLength.setWidth(60);
						
						cd_cover = new Group(searchGroupDetails,
								SWT.PUSH | SWT.CENTER);
						cd_cover.setText("");
						cd_cover.setBackground(white);
						cd_cover.setBounds(23, 23, 285, 285);
						
						delete = new Button(searchGroupResults,
								SWT.PUSH | SWT.CENTER);
						delete.setText("Delete Album");
						
						delete.addListener(SWT.Selection,
								new Listener() {
							public void handleEvent(Event event) {
								int index = searchTableAlbumResults.getSelectionIndex();
								desireCd =  Main.guiInt.getCds().get(index);
								
								
								Main.signal = new CountDownLatch(1);
								Main.dbGui.delete(ReferedObject.CD, desireCd.getAlbom_id(), Main.getUser().getUserName());
								try {
									Main.signal.await();
								} catch (InterruptedException e) {
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setText("Error");
									messageBox.setMessage("Error: "
											+ e.getLocalizedMessage());
									messageBox.open();
									e.printStackTrace();
								}

								String guiErrorMsg = Main.guiInt.getMassage();
								if (guiErrorMsg != null){
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setText("Song Search");
									messageBox.setMessage("Error: "
											+ guiErrorMsg);
									messageBox.open();
								}else{	
									TableItem[] items = searchTableAlbumResults.getSelection();
									if (items.length == 0) return;
									items[0].dispose();
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setMessage("Album deleted seccesesfuly");
									messageBox.open();
								}
							}
						});
						
						update = new Button(searchGroupResults,
								SWT.PUSH | SWT.CENTER);
						update.setText("update Album");
						
						update.addListener(SWT.Selection,
								new Listener() {
							public void handleEvent(Event event) {
								int index = searchTableAlbumResults.getSelectionIndex();
								desireCd =  Main.guiInt.getCds().get(index);
								EditAlbumDialog.openLogDialog();
								
								Main.signal = new CountDownLatch(1);
								Main.dbGui.delete(ReferedObject.CD, desireCd.getAlbom_id(), Main.getUser().getUserName());
								try {
									Main.signal.await();
								} catch (InterruptedException e) {
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setText("Error");
									messageBox.setMessage("Error: "
											+ e.getLocalizedMessage());
									messageBox.open();
									e.printStackTrace();
								}

								String guiErrorMsg = Main.guiInt.getMassage();
								if (guiErrorMsg != null){
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setText("CD Search");
									messageBox.setMessage("Error: "
											+ guiErrorMsg);
									messageBox.open();
								}else{	
									TableItem[] items = searchTableAlbumResults.getSelection();
									if (items.length == 0) return;
									items[0].dispose();
									MessageBox messageBox = new MessageBox(
											AlbumSearchResultsDialog.shell, 32);
									messageBox.setMessage("Album updated seccesesfuly");
									messageBox.open();
								}
							}
						});
						
						
						
						{
							searchButtonShowLyric = new Button(searchGroupDetails,
									SWT.PUSH | SWT.CENTER);
							searchButtonShowLyric.setText("Like");
							
							searchButtonShowLyric.addListener(SWT.Selection,
									
									new Listener() {
								public void handleEvent(Event event) {
									
								
									if(isLike==true ){	
					
										Main.signal = new CountDownLatch(1);
										Main.dbGui.like_unlike(Target.CD, desireCd.getAlbom_id(), Main.getUser(), Like.UNLIKE);
										try {
											Main.signal.await();
										} catch (InterruptedException e) {
											MessageBox messageBox = new MessageBox(
													AlbumSearchResultsDialog.shell, 32);
											messageBox.setText("Error");
											messageBox.setMessage("Error: "
													+ e.getLocalizedMessage());
											messageBox.open();
											e.printStackTrace();
										}

										String guiErrorMsg = Main.guiInt.getMassage();
										if (guiErrorMsg != null){
											MessageBox messageBox = new MessageBox(
													AlbumSearchResultsDialog.shell, 32);
											messageBox.setText("Login Form");
											messageBox.setMessage("Error: "
													+ guiErrorMsg);
											messageBox.open();
										}else{
										
										isLike = !isLike;
										
										searchButtonShowLyric.setText("Like");
										searchDialogAlbumTitleText.setText("Likes: " + Main.guiInt.getLikes());
									}
									}else if(isLike==false ){
										Main.signal = new CountDownLatch(1);
										Main.dbGui.like_unlike(Target.CD, desireCd.getAlbom_id(), Main.getUser(), Like.LIKE);
										try {
											Main.signal.await();
										} catch (InterruptedException e) {
											MessageBox messageBox = new MessageBox(
													AlbumSearchResultsDialog.shell, 32);
											messageBox.setText("Error");
											messageBox.setMessage("Error: "
													+ e.getLocalizedMessage());
											messageBox.open();
											e.printStackTrace();
										}

										String guiErrorMsg = Main.guiInt.getMassage();
										if (guiErrorMsg != null){
											MessageBox messageBox = new MessageBox(
													AlbumSearchResultsDialog.shell, 32);
											messageBox.setText("Login Form");
											messageBox.setMessage("Error: "
													+ guiErrorMsg);
											messageBox.open();
										}else{
											
											isLike = !isLike;
										searchButtonShowLyric.setText("UnLike");
										searchDialogAlbumTitleText.setText("Likes: " + Main.guiInt.getLikes());
									}
								}
							}});
							}

					}

				}
			}
			dialogShell.layout();
			dialogShell.pack();
			dialogShell.setLocation(getParent().toDisplay(100, 100));
			dialogShell.open();
			Display display = dialogShell.getDisplay();


			while (!dialogShell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public static Shell getDialogShell() {
		return dialogShell;
	}

	public static void setDialogShell(Shell dialogShell) {
		AlbumSearchResultsDialog.dialogShell = dialogShell;
	}

	//	public static Button getInitDialogButtonExit() {
	//		return logDialogButtonExit;
	//	}
	//
	//	public static void setInitDialogButtonExit(Button logDialogButtonExit) {
	//		SearchDialog.logDialogButtonExit = logDialogButtonExit;
	//	}
	//
	//	public static Button getInitDialogButtonStart() {
	//		return logDialogButtonStart;
	//	}
	//
	//	public static void setInitDialogButtonStart(Button logDialogButtonStart) {
	//		SearchDialog.logDialogButtonStart = logDialogButtonStart;
	//	}

	public static Group getInitDialogGroup() {
		return logDialogGroup;
	}

	public static void setInitDialogGroup(Group logDialogGroup) {
		AlbumSearchResultsDialog.logDialogGroup = logDialogGroup;
	}

	public static Display getInitDisplay() {
		return display;
	}

	public static void setDisplay(Display display) {
		AlbumSearchResultsDialog.display = display;
	}

	public static Display getDisplay() {
		return display;
	}

	public static AlbumSearchResultsDialog getInst() {
		return inst;
	}

	public static Shell getShell() {
		return shell;
	}


	/**
	 * clear search fields
	 */
	protected static void clearSearchFields() {
		searchTextBoxArtist.setText("");
		searchTextBoxAlbum.setText("");
		searchTextBoxSong.setText("");
		searchTextBoxLyric.setText("");
		searchTextBoxGenre.setText("");
		searchTextBoxYear.setText("");
	}
	private void newEntry(String title, String artist, String genre, int year) {
		String[] data = {title,artist,genre,Integer.toString(year)};
		if (data != null) {
			TableItem item = new TableItem(searchTableAlbumResults, SWT.NONE);
			item.setText(data);
		}
	}
	private void newSongEntry(int track, String title, String artist,  int length) {
		String[] data = {Integer.toString(track), title,artist,Integer.toString(length)};
		if (data != null) {
			TableItem item = new TableItem(searchTableSongResults, SWT.NONE);
			item.setText(data);
		}
	}
}
